package com.hsnn.medstgmini.base.dict.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicCompTypeDao;
import com.hsnn.medstgmini.base.dict.model.DicCompType;
import com.hsnn.medstgmini.base.dict.model.DicCompTypeLog;
import com.hsnn.medstgmini.dao.impl.HibernateSqlUtilImpl;
import com.hsnn.medstgmini.model.Result;
import com.hsnn.medstgmini.util.Pagination;


@SuppressWarnings("deprecation")
@Repository
public class DicCompTypeDaoImpl implements DicCompTypeDao {
	private static final Logger log = LoggerFactory
			.getLogger(DicCompTypeDaoImpl.class);
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtilImpl dao;
	
	
	/**新增企业注册类型**/
	public void saveDicCompType(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		session.save(dicCompType);
		session.flush();
	}
	
	/**修改企业注册类型**/
	public void updateDicCompType(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		session.update(dicCompType);
		session.flush();
	}
	
	/**新增/修改企业注册类型**/
	public void saveOrUpdateDicCompType(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		String hql="select compRegId from DicCompType where compRegCode=:fatherCompRegCode";
		Query query = session.createQuery(hql);
		query.setString("fatherCompRegCode", dicCompType.getFatherCompRegCode());
		String st= (String) query.uniqueResult();
		dicCompType.setFatherId(st);
		if (dicCompType.getCompRegId() != null && StringUtils.isNotEmpty(dicCompType.getCompRegId())) {
			session.update(dicCompType);
			writeLog(dicCompType);
			session.flush();
		} else {
			UUID uuid = UUID.randomUUID();
			dicCompType.setCompRegId(uuid.toString());
			dicCompType.setUpdDatetime(new Date());
			session.save(dicCompType);
			writeLog(dicCompType);
			session.flush();
		}
	}
	
	/**企业注册类型作废**/
	public void disableDicCompType(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "update DicCompType  set status = :status,updDatetime=:updDatetime where compRegId = :compRegId";
		Query query = session.createQuery(hql);
		query.setString("compRegId", dicCompType.getCompRegId());
		query.setDate("updDatetime", new Date());
		query.setShort("status", dicCompType.getStatus());
		query.executeUpdate();
		writeLog(dicCompType);
		session.flush();
	}
	
	/**企业注册类型启用**/
	public void enableDicCompType(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "update DicCompType  set status = :status,updDatetime=:updDatetime where compRegId = :compRegId";
		Query query = session.createQuery(hql);
		query.setString("compRegId", dicCompType.getCompRegId());
		query.setDate("updDatetime", new Date());
		query.setShort("status", dicCompType.getStatus());
		query.executeUpdate();
		writeLog(dicCompType);
		session.flush();
	}
	
	/**查询企业注册类型详情**/
	public DicCompType getDicCompTypeById(String id) {
		Session session = sessionFactory.getCurrentSession();
		return (DicCompType) session.get(DicCompType.class, id);
	}
	
	/**检查重复**/
	@Override
	public Integer checkRepeat(String name,String value,String id,Short type) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer();
		sql.append(" select count(comp_id) from std_compinfo where "+name+" = :value and comp_id <> :id and comp_type = :compType ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("value", value);
		query.setString("id", id);
		query.setParameter("compType", type);
		return Integer.parseInt(query.uniqueResult().toString());
	}
	
	/**企业注册类型列表**/
	@SuppressWarnings("unchecked")
	@Override
	public List<Object> getDicCompTypeList(Pagination page){
		String compRegCode = page.getConditions().get("compRegCode");
		String compRegName = page.getConditions().get("compRegName");
		String status = page.getConditions().get("status");
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sb = new StringBuffer();
		
		sb.append("	 FROM                                               ")
		  .append("	(SELECT b.comp_reg_id,a.comp_reg_code father_comp_reg_code, ")
		  .append("	a.comp_reg_name father_comp_reg_name,b.comp_reg_code,       ")
		  .append("	b.comp_reg_name,b.status,a.remark father_remark,b.remark remark FROM dic_comptype a                ")
		  .append("	INNER JOIN dic_comptype b ON a.comp_reg_id=b.father_id      ")
		  .append("	UNION                                                       ")
		  .append("	SELECT comp_reg_id,comp_reg_code father_comp_reg_code,      ")
	      .append("	comp_reg_name father_comp_reg_name,NULL,NULL,STATUS,remark father_remark,NULL         ")
	      .append("	FROM dic_comptype WHERE father_id='0')t   where 1=1         ");
		if(StringUtils.isNotBlank(compRegCode)){
			sb.append(" and (t.comp_reg_code = :compRegCode or t.father_comp_reg_code =:compRegCode) ");
		}
		if(StringUtils.isNotBlank(compRegName)){
			sb.append(" and (t.comp_reg_name like :compRegName or t.father_comp_reg_name like :compRegName)  ");
		}
		if(StringUtils.isNotBlank(status)){
			sb.append(" and (t.status = :status)  ");
		}
		StringBuffer sql = new StringBuffer();
		StringBuffer sqlCount = new StringBuffer();
		sql.append("select * ")
			.append(sb.toString());
		sqlCount.append("select count(*) ")
				.append(sb.toString());
		sql.append(" ORDER BY t.father_comp_reg_code ASC,t.comp_reg_code ASC ");
		Query query = session.createSQLQuery(sql.toString());
		Query queryCount = session.createSQLQuery(sqlCount.toString());
		if(StringUtils.isNotBlank(compRegCode)){
			query.setString("compRegCode", compRegCode);
			queryCount.setString("compRegCode", compRegCode);
		}
		if(StringUtils.isNotBlank(compRegName)){
			query.setString("compRegName", "%"+compRegName+"%");
			queryCount.setString("compRegName", "%"+compRegName+"%");
		}
		if(StringUtils.isNotBlank(status)){
			query.setString("status", status);
			queryCount.setString("status", status);
		}
		page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<DicCompType> getDicCompTypeList(Result result, DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sb = new StringBuffer();
		//查询总记录数
		sb.append("select count(*) from DicCompType d1, DicCompType d2 ");
		sb.append("where d2.fatherId = d1.compRegId ");
		
		if (dicCompType != null) {
			if (dicCompType.getCompRegCode() != null && StringUtils.isNotEmpty(dicCompType.getCompRegCode())) {
				sb.append("and d2.compRegCode like :compRegCode ");
			}
			if (dicCompType.getCompRegName() != null && StringUtils.isNotEmpty(dicCompType.getCompRegName())) {
				sb.append("and d2.compRegName like :compRegName ");
			}
		}
		Query query = session.createQuery(sb.toString());
		if (dicCompType != null) {
			if (dicCompType.getCompRegCode() != null && StringUtils.isNotEmpty(dicCompType.getCompRegCode())) {
				query.setString("compRegCode", "%"+dicCompType.getCompRegCode().trim()+"%");
			}
			if (dicCompType.getCompRegName() != null && StringUtils.isNotEmpty(dicCompType.getCompRegName())) {
				query.setString("compRegName", "%"+dicCompType.getCompRegName().trim()+"%");
			}
		}
		Long total = (Long) query.uniqueResult();
		result.setRecords(total);
		
		// 查询分页数据
		sb.setLength(0);//清空sb
		sb.append("select new DicCompType (");
		sb.append("d2.compRegId, ");
		sb.append("d2.compRegCode, ");
		sb.append("d2.compRegName, ");
		sb.append("d2.fatherId, ");
		sb.append("d2.remark, ");
		sb.append("d2.status, ");
		sb.append("d2.updDatetime, ");
		sb.append("d2.updUser, ");
		sb.append("d2.sortId, ");
		sb.append("d1.compRegCode as fatherCompRegCode, ");
		sb.append("d1.compRegName as fatherCompRegName ) ");
		sb.append("from DicCompType as d1, DicCompType as d2 ");
		sb.append("where d1.compRegId = d2.fatherId ");
		
		//查询条件
		if (dicCompType.getCompRegCode() != null && StringUtils.isNotEmpty(dicCompType.getCompRegCode())) {
			sb.append("and d2.compRegCode like :compRegCode ");
		}
		if (dicCompType.getCompRegName() != null && StringUtils.isNotEmpty(dicCompType.getCompRegName())) {
			sb.append("and d2.compRegName like :compRegName ");
		}
		sb.append("order by d2.compRegCode asc");
		query = session.createQuery(sb.toString());
		
		if (dicCompType.getCompRegCode() != null && StringUtils.isNotEmpty(dicCompType.getCompRegCode())) {
			query.setString("compRegCode",dicCompType.getCompRegCode().trim());
		}
		if (dicCompType.getCompRegName() != null && StringUtils.isNotEmpty(dicCompType.getCompRegName())) {
			query.setString("compRegName", "%"+dicCompType.getCompRegName().trim()+"%");
		}
		
		query.setFirstResult(result.getStart());
		query.setMaxResults(result.getPagesize());
		return query.list();
	}

	
	@SuppressWarnings("unchecked")
	public List<DicCompType> getDicCompTypeFullList() {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from DicCompType d where d.fatherId='0'";
		Query query = session.createQuery(hql);
		return query.list();
	}
	/**
	 * @category 根据CompRegName查询CompRegId
	 * @author 韩守松
	 * @date   2015年6月13日
	 * @param  @param dicCompType
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public List<DicCompType> getDicCompTypeByCompRegName(DicCompType dicCompType) {
		try{
			String compRegName = dicCompType.getCompRegName();
			Session session = sessionFactory.getCurrentSession();
			StringBuffer hql = new StringBuffer();
			hql.append("from DicCompType d where d.compRegName= ?") ;
			Query query = session.createQuery(hql.toString());
			query.setParameter(0, compRegName);
			return query.list();
		}catch(Exception e){
			log.info("根据企业类型名称获取企业注册类型列表失败",e);
			return new ArrayList<DicCompType>();
		}
	}


	/**
	 * @category 企业注册类型查询联动
	 * @author 韩守松
	 * @date   2015年6月29日
	 * @param  @param FatherId
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public List<DicCompType> getDicCompTypeListByFatherId(String FatherId) {
		StringBuffer hql = new StringBuffer();
		hql.append("from DicCompType dc where 1=1 and status=1");
		if(StringUtils.isNotEmpty(FatherId) && "0".equals(FatherId)){
			hql.append(" and dc.fatherId = '0' ");
		}
		if(StringUtils.isNotEmpty(FatherId) && !"0".equals(FatherId)){
			hql.append(" and dc.fatherId = :FatherId ");
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql.toString());
		if(StringUtils.isNotEmpty(FatherId) && !"0".equals(FatherId)){
			query.setParameter("FatherId", FatherId);
		}
		return query.list();
	}
	
	/**
	 * @category 企业注册类型查询联动
	 * @author 韩守松
	 * @date   2015年6月29日
	 * @param  @param FatherId
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DicCompType> getQYCompTypeListByFatherId(String FatherId) {
		StringBuffer hql = new StringBuffer();
		hql.append("from DicCompType dc where dc.status=1 ");
		if(StringUtils.isNotEmpty(FatherId) && "0".equals(FatherId)){
			hql.append(" and dc.fatherId = '0' ");
		}
		if(StringUtils.isNotEmpty(FatherId) && !"0".equals(FatherId)){
			hql.append(" and dc.fatherId = :FatherId ");
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql.toString());
		if(StringUtils.isNotEmpty(FatherId) && !"0".equals(FatherId)){
			query.setParameter("FatherId", FatherId);
		}
		return query.list();
	}

	
	/**
	 * @category 记录日志表
	 * @param dicPhar
	 */
	private void writeLog(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		DicCompType dp = getDicCompTypeById(dicCompType.getCompRegId());
		if (dp != null) {
			DicCompTypeLog dpl = new DicCompTypeLog();
			dpl.setLogId(UUID.randomUUID().toString());
			BeanUtils.copyProperties(dp,dpl);
			session.save(dpl);
		}
	}
	/**
	 * 
	 *@category 启用和停用
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("unchecked")
	@Override
	public int changeStatus(DicCompType dicCompType) {
		Session session = sessionFactory.getCurrentSession();
		List<String> list = new ArrayList<String>();
		if("0".equals(dicCompType.getStatus()+"")){
			StringBuffer sb = new StringBuffer()
			.append("select comp_reg_id from dic_comptype where comp_reg_id= :compRegId or (father_id=:compRegId and status <> 0 ) ");
			Query query = session.createSQLQuery(sb.toString());
			query.setString("compRegId", dicCompType.getCompRegId());
			List<Object> data = query.list();
			for(int i = 0;i<data.size();i++){
				list.add(data.get(i).toString());
			}
		}
		StringBuffer sql = new StringBuffer();
		sql.append("update dic_comptype  set ")
		  .append(" status=:status,upd_datetime=:updDatetime,upd_user=:updUser ")
		  .append(" where comp_reg_id= :compRegId ");
		if("0".equals(dicCompType.getStatus()+"")){
			sql.append(" or (father_id=:compRegId and status <> 0 )");
		}
		Query update = session.createSQLQuery(sql.toString());
		update.setLong("status",dicCompType.getStatus());
		update.setTimestamp("updDatetime", new Date());
		update.setString("updUser", dicCompType.getUpdUser());
		update.setString("compRegId", dicCompType.getCompRegId());
		int count = update.executeUpdate();
		session.flush();
		writeLog(dicCompType.getStatus()+"",dicCompType.getCompRegId(),list);
		return count;
	}
	
	/**
	 * 
	 *@category 写日志
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void writeLog(String status,String id,List<String> idList){
		Session session = sessionFactory.getCurrentSession();
		StringBuffer detail = new StringBuffer();
		if(!"0".equals(status)){
			StringBuffer sb = new StringBuffer()
			.append("select comp_reg_code compRegCode,comp_reg_name compRegName,status,remark from dic_comptype where comp_reg_id = :id ")
			.append(" union all ")
			.append(" select t.* from (select comp_reg_code compRegCode,comp_reg_name compRegName,status,remark from dic_comptype_log where  comp_reg_id = :id order by upd_datetime desc limit 1) t");
			Query query1 = session.createSQLQuery(sb.toString());
			query1.setString("id", id);
			query1.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			List<Map<String,Object>> list = query1.list();
			if(list.size()==1){
				detail.append("编码,")
				      .append(list.get(0).get("compRegCode").toString())
				      .append(";名称,")
				      .append(list.get(0).get("compRegName").toString())
				      .append(";状态,启用")
				      .append(";备注,")
				      .append(list.get(0).get("remark").toString());
			}else{
				if(!list.get(0).get("compRegCode").toString().equals(list.get(1).get("compRegCode").toString())){
					detail.append(";编码,")
					      .append(list.get(0).get("compRegCode").toString())
					      .append(",")
					      .append(list.get(1).get("compRegCode").toString());
				}
				if(!list.get(0).get("compRegName").toString().equals(list.get(1).get("compRegName").toString())){
					detail.append(";名称,")
					      .append(list.get(0).get("compRegName").toString())
					      .append(",")
					      .append(list.get(1).get("compRegName").toString());
				}
				if(!list.get(0).get("status").toString().equals(list.get(1).get("status").toString())){
					detail.append(";状态,")
					      .append("1".equals(list.get(0).get("status").toString())?"启用":"停用")
					      .append(",")
					      .append("1".equals(list.get(1).get("status").toString())?"启用":"停用");
				}
				if(!list.get(0).get("remark").toString().equals(list.get(1).get("remark").toString())){
					detail.append(";备注,")
					      .append(list.get(0).get("remark").toString())
					      .append(",")
					      .append(list.get(1).get("remark").toString());
				}
				detail.delete(0, 1);
			}
			
		}
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dic_comptype_log(log_id,comp_reg_id,comp_reg_code,comp_reg_name,  ")
		   .append("father_id,remark,status,upd_datetime,upd_user,sort_id,detail) select ")
		   .append(" UUID(),t.*,:detail from dic_comptype t where t.comp_reg_id= :id ");
		if("0".equals(status)){
			sql.append(" or t.comp_reg_id in (:idList)");
			//字段名,修改后数据,修改前数据
			detail.append("状态,停用,启用");
			
		}
		Query query=session.createSQLQuery(sql.toString());
		query.setString("id",id);
		if("0".equals(status)){
			query.setParameterList("idList", idList);
		}
		query.setString("detail", detail.toString());
		query.executeUpdate();
		session.flush();
		
	}
	//查询
	@Override
	public Pagination initEdit(Pagination page){
		String compRegId = page.getConditions().get("compRegId");
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT b.comp_reg_code fatherCompRegCode,b.comp_reg_name fatherCompRegName,a.comp_reg_code compRegCode,a.comp_reg_name  compRegName,b.remark fatherRemark,  ")
		   .append(" a.remark remark FROM dic_comptype a LEFT JOIN dic_comptype b ON a.father_id = b.comp_reg_id WHERE a.comp_reg_id =:compRegId ");
		Query query=session.createSQLQuery(sql.toString());
		query.setString("compRegId",compRegId);
		page.setRows(query.uniqueResult());
		return page;
	}
	//编辑
	@Override
	public void updateCompType(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String compRegCode = page.getConditions().get("compRegCode");
		String compRegName = page.getConditions().get("compRegName");
		String compRegId = page.getConditions().get("compRegId");
		String remark = page.getConditions().get("remark");
		String updUser = page.getConditions().get("updUser");
		StringBuffer sql = new StringBuffer();
		sql.append(" update dic_comptype set comp_reg_code=:compRegCode, ")
		   .append("comp_reg_name=:compRegName,upd_datetime=:updDatetime,")
		   .append(" upd_user=:updUser ,remark=:remark where comp_reg_id=:compRegId      ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("compRegCode",compRegCode );
		query.setString("compRegName",compRegName );
		query.setString("remark",remark );
		query.setString("updUser",updUser );
		query.setTimestamp("updDatetime", new Date());
		query.setString("compRegId", compRegId);
		query.executeUpdate();
		session.flush();
		writeLog("1",compRegId,null);
	}
	
	/**
	 * 根据code或name查看有无重复数据
	 * @param code,name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DicCompType> getCompTypeBy(String key,String value,String compRegId) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from dic_comptype where ")
		   .append(key)
		   .append(" = ? and  comp_reg_id <> ? ");
		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql.toString());
		query.setParameter(0, value);
		query.setParameter(1,compRegId);
		return query.list();
	}
	//编辑
	@Override
	public void addCompType(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String compRegCode = page.getConditions().get("compRegCode");
		String compRegName = page.getConditions().get("compRegName");
		String updUser = page.getConditions().get("updUser");
		String fatherId = page.getConditions().get("fatherId");
		String compRegId = page.getConditions().get("compTypeAddId");
		String remark = page.getConditions().get("remark");
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dic_comptype(comp_reg_id,comp_reg_code,comp_reg_name,father_id,  ")
		   .append("status,upd_datetime,upd_user,remark) values ( ")
		   .append(":compRegId,:compRegCode,:compRegName,:fatherId,1,:updDatetime,:updUser,:remark ) ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("compRegCode",compRegCode );
		query.setString("compRegName",compRegName );
		query.setString("updUser",updUser );
		query.setString("remark",remark );
		query.setTimestamp("updDatetime", new Date());
		query.setString("fatherId", fatherId);
		//String compRegId = UUID.randomUUID().toString();
		query.setString("compRegId", compRegId);
		query.executeUpdate();
		session.flush();
		writeLog("1",compRegId,null);
	}
	
	/**
	 * 根据条件获取不分页数据
	 * @param page
	 * @return page
	 */
	@Override
	public Pagination getDicCompTypeNoPage(Pagination page){
		String compRegCode = page.getConditions().get("compRegCode");
		String compRegName = page.getConditions().get("compRegName");
		String status = page.getConditions().get("status");
		StringBuffer sql = new StringBuffer();
		sql.append("    select * FROM                                               ")
		   .append("	(SELECT a.comp_reg_code fatherCompRegCode, ")
		   .append("	a.comp_reg_name fatherCompRegName,b.comp_reg_code compRegCode,       ")
		   .append("	b.comp_reg_name compRegName,case b.status when '0' then '停用' else '启用' end status,b.remark remark FROM dic_comptype a                ")
		   .append("	INNER JOIN dic_comptype b ON a.comp_reg_id=b.father_id      ")
		   .append("	UNION                                                       ")
		   .append("	SELECT comp_reg_code fatherCompRegCode,      ")
	       .append("	comp_reg_name fatherCompRegName,NULL compRegCode,NULL compRegName,case status when '0' then '停用' else '启用' end status,remark         ")
	       .append("	FROM dic_comptype WHERE father_id='0')t   where 1=1         ");
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(compRegCode)){
			sql.append(" and (t.compRegCode = :compRegCode or t.fatherCompRegCode =:compRegCode) ");
			params.put("compRegCode", compRegCode);
		}
		if(StringUtils.isNotBlank(compRegName)){
			sql.append(" and (t.compRegName like :compRegName or t.fatherCompRegName like :compRegName)  ");
			params.put("compRegName", "%"+compRegName+"%");
		}
		if(StringUtils.isNotBlank(status)){
			sql.append(" and (t.status = :status)  ");
			params.put("status", "0".equals(status)?"停用":"启用");
		}
		
		sql.append(" ORDER BY t.fatherCompRegCode ,t.compRegCode ");
		page.setRows(dao.getSqlMapList(sql.toString(), params));
		return page;
	}
}
